package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于死信交换机
 *
 * 基于配置文件（强）
 *  bean.xml  <bean class ...
 *  SpringBoot项目  基于JavaBean   @Configuration
 *
 */
@Configuration
public class DeadLetterExchange {
    public static final String exchange_dead = "exchange.dead";// 公用的交换机
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";


    //配置一个交换机
    @Bean
    public DirectExchange exchange(){
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }
    //延迟队列
    @Bean
    public Queue delayQueue(){
        Map<String, Object> arguments = new HashMap<>();
        //存活时间  ttl  毫秒
        // 全局设置   取消订单 2小时   支付 3小时必须付钱
        // 局部可以设置 时间    优先级是局部最高
        arguments.put("x-message-ttl", 10 * 1000);
        //过期转发到哪个交换机
        arguments.put("x-dead-letter-exchange", exchange_dead);
        // 哪个RoutingKey
        arguments.put("x-dead-letter-routing-key", routing_dead_2);

        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }
    //普通 正常队列
    @Bean
    public Queue queue(){
        return QueueBuilder.durable(queue_dead_2).build();
    }
    //绑定
    @Bean
    public Binding bindingDelayQueueToExchange(){
        return BindingBuilder.bind(delayQueue()).to(exchange()).with(routing_dead_1);
    }
    //绑定
    @Bean
    public Binding bindingQueueToExchange(){
        return BindingBuilder.bind(queue()).to(exchange()).with(routing_dead_2);
    }
}
